package com.itheima.web.realm;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.domain.system.Module;
import com.itheima.domain.system.User;
import com.itheima.service.system.UserService;
import com.itheima.web.utils.SpringUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class SaasRealm extends AuthorizingRealm {

//    @Reference
//    private UserService userService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("=====================================进入认证方法了===================================");

        //提取用户名
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        String email = usernamePasswordToken.getUsername();

        //查询用户信息
        UserService userService = (UserService) SpringUtil.getBean("userService");
        User user = userService.findByEmail(email);

        if (user == null) {
            return new SimpleAuthenticationInfo();
        } else {
            //主角
            //密码
            //当前Realm的名称
            return new SimpleAuthenticationInfo(user, user.getPassword(), this.getName());
        }
    }


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("=====================================进入授权方法了===================================");

        //获取会话中的user
        User user = (User) principalCollection.getPrimaryPrincipal();

        //查询当前用户拥有的权限
        UserService userService = (UserService) SpringUtil.getBean("userService");
        List<Module> moduleList = userService.findModuleByUser(user);

        // 告诉shiro权限
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        for (Module module : moduleList) {
            authorizationInfo.addStringPermission(module.getName());
        }

        //打印一下, 当前告诉Shiro的权限
        System.out.println("=====================当前用户的权限列表:" + authorizationInfo.getStringPermissions());

        return authorizationInfo;
    }
}
